<template>
  <div class="x_panel">
    <el-form :inline="true" :model="search" label-width="90px">
      <el-form-item label="项目名称：">
        <el-input v-model="search.itemName" style="width: 150px" placeholder />
      </el-form-item>
      <el-form-item label="所属业务：">
        <el-select
          v-model="filterbusinessType"
          style="width: 120px"
          placeholder="所属业务"
        >
          <el-option
            v-for="item in filterBizList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item style="margin-left: 5px">
        <el-button
          class="btn_YUP"
          type="primary"
          icon="el-icon-search"
          @click="query"
        >
          查询
        </el-button>
      </el-form-item>
      <el-form-item style="margin-left: 20px">
        <el-button class="btn_YUP" icon="el-icon-plus" @click="openAdd">
          创建项目
        </el-button>
      </el-form-item>
    </el-form>

    <el-card
      v-loading="loading"
      class="box-card"
    >
      <div v-if="tableData.length === 0" style="text-align: center">
        暂无项目
      </div>
      <div class="list">
        <el-table :data="tableData" border align="center" class="my_table" height="calc(100vh- 200px)">
          <el-table-column label="项目名称" prop="itemName" align="center" />
          <el-table-column label="缩略图" align="center">
            <template slot-scope="scope">
              <img
                class="img_inner"
                :src="scope.row.primaryPicture ? scope.row.primaryPicture : '/images/common/default.png'"
              />
            </template>
          </el-table-column>
          <el-table-column label="业务部门" prop="department" align="center" />
          <el-table-column label="活动数量" prop="totalNum" align="center" />
          <el-table-column label="线上活动" prop="onlineNum" align="center" />
          <el-table-column label="近期上线情况" align="center">
            <template slot-scope="scope">
              <div
                v-for="(child, index) in scope.row.schedules"
                :key="index"
                class="hd-table-block"
              >
                <div class="date_box">
                  日期：{{ child.date ? child.date : '未知' }}
                </div>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                <div class="date_num">
                  上线数：{{ child.onlineNum }}
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="200">
            <template slot-scope="scope">
              <el-button
                class="btn_YUP"
                type="primary"
                size="small"
                @click="editItem(scope.row)"
              >
                查看
              </el-button>
              <el-button
                size="small"
                class="btn_YUP"
                type="primary"
                @click="editProject(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="deleteItem(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- <div
          v-for="item in tableData"
          :key="item.itemCode"
          class="project-block-b"
        >
          <div class="content">
            <div style="display: flex; justify-content: center">
              <img
                :src="
                  item.primaryPicture
                    ? item.primaryPicture
                    : '/images/common/default.png'
                "
                @click="editItem(item)"
              />
              <div v-if="getBizName(item)" class="projecttag">
                {{ getBizName(item) }}
              </div>
            </div>
            <div class="text-block">
              <div style="display: flex; justify-content: space-between">
                <div class="title">
                  {{ item.itemName }}
                </div>
              </div>

              <div class="num">
                <div>活动数量：{{ item.totalNum }}</div>
                <div>线上活动：{{ item.onlineNum }}</div>
              </div>
              <div>
                <div>业务部门：{{ item.department }}</div>
              </div>
              <div class="hd-table">
                <div class="hd-table-block-first">
                  <div class="up-box cell">
                    日期
                  </div>
                  <div class="cell">
                    当日上线数
                  </div>
                </div>
                <div
                  v-for="(child, index) in item.schedules"
                  :key="index"
                  class="hd-table-block"
                >
                  <div class="up-box cell">
                    {{ child.date ? child.date : '未知' }}
                  </div>
                  <div class="cell">
                    {{ child.onlineNum }}
                  </div>
                </div>
              </div>
              <div class="toolbar">
                <i
                  title="查看活动"
                  class="el-icon-menu"
                  @click="editItem(item)"
                ></i>
                <i
                  title="修改项目信息"
                  class="el-icon-edit"
                  @click="editProject(item)"
                ></i>
                <i
                  title="删除项目"
                  class="el-icon-delete"
                  @click="deleteItem(item)"
                ></i>
              </div>
            </div>
          </div>
        </div> -->
      </div>
    </el-card>
    <div v-if="pageShow" ref="pager" class="pager">
      <el-pagination
        background
        :current-page.sync="search.pageIndex"
        :page-size="search.length"
        layout="total,  prev, pager, next, jumper"
        :total="totalRows"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog
      :title="tag ? '修改项目' : '项目新增'"
      :visible.sync="dialogVisible"
      width="540px"
    >
      <el-form label-width="80px">
        <el-form-item label="项目名称">
          <el-input v-model="projectInfo.itemName" style="width: 80%" />
        </el-form-item>
        <el-form-item label="所属业务">
          <!-- <el-input v-model="projectInfo.businessType"  /> -->
          <el-select
            v-model="projectInfo.businessType"
            style="width: 80%"
            placeholder="请选择所属业务"
          >
            <el-option
              v-for="item in bizList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="业务部门">
          <el-input v-model="projectInfo.department" style="width: 80%" />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" class="btn_YUP" @click="saveProject">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import PageServer from '@/servers/page'
import tool from '@/util/tool'
import { bizTypeList } from '@/util/biz/bizTypeList'
import Vue from 'vue'
import 'element-ui/lib/theme-chalk/index.css'
import ElementUI,{ Loading } from 'element-ui'
Vue.use(ElementUI) 
Vue.use(Loading.directive)
export default {
  name: 'Project',
  components: { 
  },
  filters: {
    date: function (value) {
      if (!value || value === '') return ''
      let date = new Date(value)
      let o = {
        'M+': date.getMonth() + 1, 
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds(), 
        'q+': Math.floor((date.getMonth() + 3) / 3),
        S: date.getMilliseconds(),
      }
      let fmt = 'yyyy-MM-dd hh:mm:ss'
      if (/(y+)/.test(fmt))
        fmt = fmt.replace(
          RegExp.$1,
          (date.getFullYear() + '').substr(4 - RegExp.$1.length)
        )
      for (let k in o)
        if (new RegExp('(' + k + ')').test(fmt))
          fmt = fmt.replace(
            RegExp.$1,
            RegExp.$1.length === 1
              ? o[k]
              : ('00' + o[k]).substr(('' + o[k]).length)
          )
      return fmt
    },
  },
  layout: 'manageLayout',
  data () {
    return {
      cookieText:'',
      bizList: [
        ...bizTypeList
      ],
      filterBizList: [
        { label: '全部', value: 'all' },
        ...bizTypeList
      ],
      filterbusinessType: 'all',
      filteritemType: 'all',
      tag: false,
      loading: false,
      randomtxt: '',
      pageShow: true,
      search: {
        pageIndex: 1,
        itemName: null,
        start: 0,
        length: 10,
        businessType: null,
        itemType: null,
      },

      totalRows: 0,
      // 表格数据
      tableData: [],
      logData: [],
      dialogVisible: false,
      projectInfo: {
        itemType: 1,
      },
    }
  },
  mounted () {
    let from = tool.getUrlParam('from')
    if (from === 'child') {
      this.initFilters()
      this.renderDatble()
    } else {
      this.query()
    }
  },
  methods: {
    configCk(){
      document.cookie = this.cookieText
    },
    getCk(){
      alert(document.cookie)
      console.log(document.cookie)
    },
    getBizName (item) {
      if (item.businessType === null) {
        return ''
      }
      let node = this.bizList.find(
        (a) =>
          a.value === item.businessType ||
          a.value === item.businessType.toString()
      )
      if (node === null || !node) {
        return ''
      }
      return node.label
    },
    testRandom () {
      this.randomtxt = tool.guid()
    },
    openAdd () {
      this.projectInfo = {
        itemType: 1,
      }
      this.dialogVisible = true
      this.tag = false
    },
    editProject (row) {
      this.projectInfo = JSON.parse(JSON.stringify(row))
      this.dialogVisible = true
      this.tag = true
    },
    saveFilters () {
      this.search.itemType =
        this.filteritemType === 'all' ? null : this.filteritemType
      this.search.businessType =
        this.filterbusinessType === 'all' ? null : this.filterbusinessType
      localStorage.setItem('projectFilters', JSON.stringify(this.search))
    },
    initFilters () {
      this.pageShow = false
      let model = JSON.parse(localStorage.getItem('projectFilters'))
      this.search = model
      this.filteritemType = model.itemType === null ? 'all' : model.itemType
      this.filterbusinessType =
        model.businessType === null ? 'all' : model.businessType
      this.$nextTick(() => {
        this.pageShow = true
      })
    },
    saveProject () {
      let _this = this
      if (!this.projectInfo.itemName) {
        _this.$message.error('项目名称必填！')
        return
      }

      if (typeof (this.projectInfo.businessType) === 'undefined') {
        _this.$message.error('所属业务必选！')
        return
      }
      if (!this.projectInfo.department) {
        _this.$message.error('业务部门必填！')
        return
      }

      if (this.projectInfo.itemCode) {
        // edit
        PageServer.updateItem(this.projectInfo).then((res) => {
          if (res.flag === 'S') {
            _this.$message.info('修改成功！')
            _this.dialogVisible = false
            _this.search.pageIndex = 1
            _this.renderDatble()
          }
        })
      } else {
        // add
        PageServer.saveItem({ ...this.projectInfo, isNew: 1 }).then((res) => {
          if (res.flag === 'S') {
            _this.$message.info('保存成功！')
            _this.dialogVisible = false
            _this.search.pageIndex = 1
            _this.renderDatble()
          }
        })
      }

    },
    editItem (row) {
      this.saveFilters()
      location.href = `/management/activity?itemCode=${row.itemCode}&itemName=${ row.itemName}&shiro_sid=${tool.getUrlParam('shiro_sid')}&token=${tool.getUrlParam('token')}`
    },
    handleCurrentChange (val) {
      this.search.pageIndex = val
      this.renderDatble()
    },
    deleteItem (item) {
      this.$confirm(
        '删除后该项目后，项目中的活动会全部被删除，是否继续？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        this.saveDelete(item)
      })
    },
    saveDelete (item) {
      PageServer.deleteItem({ itemCode: item.itemCode }).then((res) => {
        if (res.flag === 'S') {
          this.$message.info('删除成功！')
          this.search.page = 1
          this.search.pageIndex = 1
          this.renderDatble()
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    renderDatble () {
      console.log('=====请求接口前获取到的cookie=======')
      console.log(document.cookie)
      console.log('=====请求接口前获取到的cookie=======')
      this.loading = true
      this.search.start = (this.search.pageIndex - 1) * this.search.length
      let filters = JSON.parse(JSON.stringify(this.search))
      filters.itemName = filters.itemName ? filters.itemName : null

      filters.itemType =
        this.filteritemType === 'all' ? null : this.filteritemType
      filters.businessType =
        this.filterbusinessType === 'all' ? null : this.filterbusinessType
      PageServer.queryItemListNew(filters).then((res) => {
        if (res.flag === 'S') {
          this.loading = false
          this.tableData = res.data.rows
          this.totalRows = res.data.total
        }
      })
    },
    query () {
      this.search.start = 0
      this.search.pageIndex = 1
      this.renderDatble()
    },
  },
}
</script>


<style lang="less" scoped>
@import './index.less';
</style>

